let templateIds = [];//定义一个数组
let templateForButtonIds = [];//定义一个数组
let templateNameArr = [];
$(document).ready(function () {

    // 菜单点击切换
    $(".menuLi").on('click', function (e) {
        //打开对应页面
        let url = $(this).attr("value");
        let templateName = $(this).attr("classid");
        let prescriptionTemplateId = $(this).attr("data");

        //获取当前选中
        let curClass = $(this).attr("class")
        if (curClass.indexOf("selectMenu") >= 0) {
            $(this).removeClass("selectMenu");
            templateIds.splice(jQuery.inArray(prescriptionTemplateId, templateIds), 1);
        } else {
            $(this).addClass("selectMenu");
            templateIds.push(prescriptionTemplateId);
        }
        $('#prescriptionTemplateId').val(templateIds);
        $('#selectPrescriptionTemplateH4').text(templateName);
        $(".templatePicImg").attr('src', url);
    });

    // 菜单点击切换
    $(".menuLiForButton").on('click', function (e) {
        let url = $(this).attr("value");
        let templateName = $(this).attr("classid");
        let prescriptionTemplateId = $(this).attr("data");
        //获取当前选中
        let curClass = $(this).attr("class")
        if (curClass.indexOf("selectMenu") >= 0) {
            $(this).removeClass("selectMenu");
            $(this).addClass("menuLiForButton");
            templateNameArr.splice(jQuery.inArray(templateName, templateNameArr), 1);
            templateForButtonIds.splice(jQuery.inArray(prescriptionTemplateId, templateForButtonIds), 1);
        } else {
            $(this).addClass("selectMenu");
            $(this).removeClass("menuLiForButton");
            templateForButtonIds.push(prescriptionTemplateId);
            templateNameArr.push(templateName);
        }
        $('#selectTempleSpan').text("已选" + templateNameArr.length + "个模板");
        $('#selectTemplateForButtonH4').text(templateName);
        $(".templatePicImgForButton").attr('src', url);
    });
    //默认选中第一个菜单
    if ($(".menuLiForButton").get(0) != undefined) {
        $(".menuLiForButton").get(0).click();
    }

    //加载数据
    loadData();
    // 搜索按钮
    $("#search").on('click', function (e) {
        //重置页码
        $("#pageNum").val(1);
        //查询数据
        loadData();
    });


    //下载模板
    $(".downTemplate").on('click', function (e) {
        var url = "institutionalInfo/downloadTemplate";
        WeKnow.location(url);
        WeKnow.closeLoading();
    });

    // 导入机构和医生
    $(".importInfo").on('click', function (e) {
        $("#importExcelFile").click();
    });


    $("#importExcelFile").on('change', function () {
        var formData = new FormData();
        formData.append("importExcelFile", this.files[0]); //加入文件对象
        WeKnow.loading();
        $.ajax({
            type: "POST",
            url: "institutionalInfo/importExcel",
            dataType: "json",
            data: formData,
            async: false,
            processData: false,//用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            success: function (data) {
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                if (data.errCode == 0) {
                    WeKnow.errorMsg(data.errMsg);
                } else {
                    WeKnow.successMsg("导入成功!");
                }
            },
            error: function () {
                WeKnow.systemMsg('系统异常');
            },
            complete: function () {
                WeKnow.closeLoading();
                $("#importExcelFile").val("");
            }
        });

    })


    // 添加处方模板弹窗
    $(".addPrescriptionTemplate").on('click', function (e) {
        //弹出窗口
        $('#addPrescriptionTemplateDiv').modal('show');
    });

    //保存机构
    $('#saveInstitutionalLink').on('click', function () {
        saveInstitutional();
    });

    //保存处方模板
    $('#savePrescriptionTemplate').on('click', function () {
        savePrescriptionTemplate();
    });

    //匹配处方模板
    $('#selectedPrescriptionTemplate').on('click', function () {
        selectedPrescriptionTemplate();
    });


    //limit变更
    $("#pageSize").on('change', function (e) {
        //重置页码
        $("#pageNum").val(1);
        //查询数据
        loadData();
    });


});

//总页数
let allPage = 1;

//加载数据
function loadData() {
    //获取请求参数
    let loadParams = getLoadParams();
    WeKnow.loading();
    //请求接口
    $.ajax({
        type: "POST",
        url: "institutionalInfo/institutionalInfoList",
        dataType: "json",
        data: loadParams,
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode === 1) {
                let $orgBody = $('#tbodyInstitutionalInfoList');
                $orgBody.empty();
                let dataInfo = data.selectHealthManageList;
                if (dataInfo && dataInfo.length) {
                    let e = '';
                    $(dataInfo).each(function (idx, rowData) {
                        e += '<tr data-template_pic_url="' + rowData.templatePicUrl + '"  data-institution_id="' + rowData.id + '">';
                        //序号
                        e += '<td class="text-center">' + (idx + 1) + '</td>';
                        // 机构名称
                        e += '<td class="text-center">' + (rowData.name ? rowData.name : "-") + '</td>';
                        // 机构地址
                        e += '<td class="text-center">' + (rowData.address ? rowData.address : "-") + '</td>';
                        // 负责人
                        e += '<td class="text-center">' + (rowData.ownerName ? rowData.ownerName : "-") + '</td>';
                        // 联系电话
                        e += '<td class="text-center">' + (rowData.tel ? rowData.tel : "-") + '</td>';
                        // 上传处方
                        e += '<td class="text-center" style="color: blue">' + (rowData.uploadNum ? rowData.uploadNum : "-") + '</td>';
                        // 违规处方
                        e += '<td class="text-center" style="color: red">' + (rowData.violationNum ? rowData.violationNum : "-") + '</td>';

                        if (rowData.templatePicUrl != null) {
                            // 处方模板
                            e += '<td class="text-center">';
                            e += '<a href="#"><span class="showPrescriptionTemplateSpan">查看</span></a>';
                            e += '</td>';
                            // 操作
                            e += '<td class="text-center">';
                            e += '<a href="#"><span class="matchPrescriptionTemplateSpan">重新匹配处方模板</span></a>';
                            e += '</td>';
                        } else {
                            // 处方模板
                            e += '<td class="text-center">';
                            e += '<a href="#"><span class="">/</span></a>';
                            e += '</td>';
                            // 操作
                            e += '<td class="text-center">';
                            e += '<a href="#"><span class="matchPrescriptionTemplateSpan">匹配处方模板</span></a>';
                            e += '</td>';
                        }


                        e += '</tr>';
                    });
                    $orgBody.append(e);
                } else {
                    WeKnow.notifyMsg('暂无数据');
                }
                //页码修改
                if (allPage != data.pages) {
                    allPage = data.pages;
                    //重新生成页面下拉
                    let $selectPage = $('#selectPage');
                    $selectPage.empty();
                    let e = '';
                    for (let i = 1; i <= allPage; i++) {
                        e += '<option value="' + i + '">' + i + '</option>';
                    }
                    $selectPage.append(e);
                    //总页码
                    $(".allPage").html("共" + allPage + "页");
                }
                //限制上一页
                if (loadParams.pageNum == 1) {
                    $(".upPageDiv").html('上一页');
                } else {
                    $(".upPageDiv").html('<a href="javascript:updatePage(' + (parseInt(loadParams.pageNum) - 1) + ')">上一页</a>');
                }
                //限制下一页
                if (loadParams.pageNum >= allPage) {
                    $(".downPageDiv").html('下一页');
                } else {
                    $(".downPageDiv").html('<a href="javascript:updatePage(' + (parseInt(loadParams.pageNum) + 1) + ')">下一页</a>');
                }
                //修改当前页码
                $("#selectPage").val(loadParams.pageNum);
            } else if (data.errCode === -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }, complete: function () {
            WeKnow.closeLoading();
        }
    });

}

//页面变更
$("#selectPage").on('change', function (e) {
    updatePage($(this).val())
});


//修改页码
function updatePage(pageNum) {
    //获取页码
    $("#pageNum").val(pageNum);
    //查询数据
    loadData();
}

//获取 加载数据集合 入参
function getLoadParams() {
    let params = {};
    //账号名称
    params.institutionalName = $("#institutionalName").val();
    //页面
    params.pageNum = $("#pageNum").val();
    //一页数据加载数(limit)
    params.pageSize = $("#pageSize").val();
    return params;
}


//查看模板
$("#tbodyInstitutionalInfoList").on('click', '.showPrescriptionTemplateSpan', function (e) {
    //获取数据
    let $parentTr = $(this).closest('tr');
    MY_SHOW_IMG.showImg($parentTr.data('template_pic_url'), 1);
});

//选择模板
$("#tbodyInstitutionalInfoList").on('click', '.matchPrescriptionTemplateSpan', function (e) {
    let $parentTr = $(this).closest('tr');
    let institutionId = $parentTr.data('institution_id');
    $('#prescriptionTemplateInstitutionId').val(institutionId);
    $(".menuLi").removeClass("selectMenu");
    templateIds = [];
    $.ajax({
        type: "POST",
        url: "institutionalInfo/getTemplatesByInstitutionId",
        dataType: "json",
        data: {"institutionId": institutionId},
        async: true,//异步调用
        success: function (data) {
            if (data.errCode == 1) {
                let isDefault = true;
                let menuLength = $('.menuLi').length
                let dataInfo = data.institutionTemplates;
                $(dataInfo).each(function (idx, rowData) {
                    let templateSign = rowData.templateSign;
                    for (let i = 0; i < menuLength; i++) {
                        $('.menuLi').get(i);
                        let bgcolor = $('.menuLi').get(i).attributes[1].value;
                        if (templateSign == bgcolor) {
                            isDefault = false;
                            $(".menuLi").get(i).click();
                        }
                    }
                });
                //默认选中第一个菜单
                if (isDefault) {
                    if ($(".menuLi").get(0) != undefined) {
                        $(".menuLi").get(0).click();
                    }
                }
                $('#selectPrescriptionTemplateDiv').modal('show');
            }
        }
    });

});


//添加机构
function saveInstitutional() {
    //获取参数
    let params = getSaveInstitutionalParams();
    if (params) {
        WeKnow.loading();
        //请求接口
        $.ajax({
            type: "POST",
            url: "institutionalInfo/saveInstitutionalInfo",
            dataType: "json",
            data: JSON.stringify(params),
            contentType: "application/json",
            async: true,//异步调用
            success: function (data) {
                WeKnow.closeLoading();
                if (data.errCode == 1) {
                    //请求成功重新加载页面
                    window.location.reload();
                } else if (data.errCode == -1) {
                    window.parent.WeKnow.location("loginTimeout");
                } else {
                    WeKnow.errorMsg(data.errMsg);
                }
            }
        });
    }
}


//添加处方模板
function savePrescriptionTemplate() {
    //获取参数
    let templateSign = $("#templateSign").val();//模板id
    let templateName = $("#templateName").val();//模板名称
    let file = $("#templatePic")[0].files[0];//处方图片

    //校验参数
    if (file === undefined) {
        WeKnow.notifyMsg("选择处方模板图片")
        return null;
    }

    if (!templateSign || !templateName) {
        WeKnow.notifyMsg("参数不能为空")
        return null;
    }


    let formData = new FormData();
    formData.append('file', file);
    formData.append('templateSign', templateSign);
    formData.append('templateName', templateName);
    WeKnow.loading();
    $.ajax({
        url: "institutionalInfo/savePrescriptionTemplate",														//后台接收数据地址
        data: formData,
        type: "POST",
        dataType: "json",
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false,
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode === 0) {
                $('#addPrescriptionTemplateDiv').modal("hide");
                WeKnow.successMsg(data.errMsg)
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });
}

//获取 加载数据集合 入参
function getSaveInstitutionalParams() {
    let params = {};
    params.institutionalId = $("#addInstitutionalId").val();//机构id
    params.name = $("#addInstitutionalName").val();//机构名称
    params.address = $("#address").val();//机构地址
    params.ownerName = $("#ownerName").val();//机构负责人
    params.tel = $("#tel").val();//联系电话
    params.areaCode = $('#areaCode').val();
    params.templateIds = templateForButtonIds;
    //校验参数
    if (!params.name || !params.address || !params.ownerName || !params.tel || !params.areaCode) {
        WeKnow.notifyMsg("参数不能为空")
        return null;
    }

    if (params.tel.length != 11) {
        WeKnow.notifyMsg("请输入11位用户手机");
        return null;
    }
    if (params.templateIds.length == 0) {
        WeKnow.notifyMsg("请选择模板！");
        return null;
    }
    return params;
}

//机构匹配处方
function selectedPrescriptionTemplate() {
    //获取参数
    let params = getTemplateParams();
    if (params) {
        WeKnow.loading();
        //请求接口
        $.ajax({
            type: "POST",
            url: "institutionalInfo/selectedPrescriptionTemplate",
            dataType: "json",
            data: params,
            async: true,//异步调用
            success: function (data) {
                WeKnow.closeLoading();
                if (data.errCode == 1) {
                    //请求成功重新加载页面
                    window.location.reload();
                } else if (data.errCode == -1) {
                    window.parent.WeKnow.location("loginTimeout");
                } else {
                    WeKnow.errorMsg(data.errMsg);
                }
            }
        });
    }
}


//获取 加载数据集合 入参
function getTemplateParams() {
    let params = {};
    params.templateIds = $('#prescriptionTemplateId').val();//模板id
    params.institutionId = $('#prescriptionTemplateInstitutionId').val();//机构id

    if (!params.templateIds) {
        WeKnow.notifyMsg("请选择模板！")
        return null;
    }
    return params;
}
